<template>
  <div>
    <h2 style="margin:  auto;">修改页面</h2>
    <br>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
      class="demo-ruleForm" :size="formSize" status-icon>
      <el-form-item label="姓名" prop="nickName">
        <el-input v-model="ruleForm.nickName" />
      </el-form-item>
      <el-form-item label="部门" prop="depId">
        <el-select v-model="ruleForm.depId" placeholder="请选择">
          <el-option v-for="item in depVule[0].children" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="请假类别" prop="leaveType">
        <el-radio-group v-model="ruleForm.leaveType">
          <el-radio value="事假" name="type">
            事假
          </el-radio>
          <el-radio value="病假" name="type">
            病假
          </el-radio>
          <el-radio value="婚假" name="type">
            婚假
          </el-radio>
          <el-radio value="产假" name="type">
            产假
          </el-radio>
          <el-radio value="丧假" name="type">
            丧假
          </el-radio>
          <el-radio value="补休" name="type">
            补休
          </el-radio>
          <el-radio value="工伤" name="type">
            工伤
          </el-radio>
          <el-radio value="其他" name="type">
            其他
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="请假时间" style="height: 90px; width: 600px;">
        <el-date-picker v-model="dateRange" type="datetimerange" range-separator="至" start-placeholder="开始时间"
          end-placeholder="结束时间" @change="GetDateVule" style=" width: 600px;" />
        <!-- 动态显示计算出的天数和小时数 -->
        <p style=" width: 600px;">
          共 {{ totalDays }} 天 {{ remainingHours.toString().padStart(2, '0') }} 小时
        </p>
        <p style=" width: 600px;">
          报道时间: {{ dateRange[1] ? moment(dateRange[1]).format("yyyy-MM-DD HH:mm:ss") : "未选择" }}
        </p>
      </el-form-item>
      <el-form-item label="请假事由">
        <el-input v-model="ruleForm.leaveReason" type="textarea" show-word-limit maxlength="140" />
      </el-form-item>
      <el-form-item label="部门领导">
        <el-input v-model="ruleForm.leaveLeader" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          提交
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus';
import moment from 'moment';
import { compile, computed, onMounted, reactive, ref } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from '@/stores/counter';
import DepData from '@/stores/departmentData'
import axios from 'axios';

//部门信息
const depVule = DepData;
//pini保存
const store = useCounterStore();
//跳转
const router = useRouter();
//传参
const route = useRoute();
//审批状态 是否已审批 false未审批 true已审批
const IsStatus = ref(false)



//#region 请假申请表单添加


//#region 反填

//开始结束时间存储
const UpStartTime = ref("")
const UpEndTime = ref("")


//部门领导人


//处理反填的数据
const FanTianData = () => {
  //反填时间范围
  if (route.query.leavePeriod) {
    const [Adate, Bdate] = route.query.leavePeriod.split('至');
    console.log([Adate, Bdate], "字符串转换时间")
    const Adates = moment(Adate).toDate();
    const Bdates = moment(Bdate).toDate();
    //时间参数
    dateRange.value = [Adates, Bdates]
    // console.log(dateRange.value, "时间参数")
    GetDateVule(dateRange.value);
    //反填审批结果
    FanTianStatus()
  }
}



//#endregion


//反填审批结果
const FanTianStatus = () => {
  //反填审批结果 (通过 -- 不通过)
  axios.get(`https://localhost:7174/api/Approve/FanTianAPPlicant?LeaveId=${route.query.leaveId}&UserId=${store.ccstore.userId}`).then(res => {
    RecordForm.recordStatus = res.data.data.recordStatus
    RecordForm.reason = res.data.data.recordStatus
    console.log(RecordForm.recordStatus, "反填状态")
    console.log(RecordForm.reason, "反填拒绝原因")
    //状态 1未审批 2已审批
    if (RecordForm.recordStatus) {
      //修改为已审批
      IsStatus.value = true
      console.log(IsStatus.value, "修改为已审批")
    }
    if (!RecordForm.recordStatus) {
      //修改为未审批
      IsStatus.value = false
    }

  })
}





//#region  时间计算

//定义一个响应式变量来存储日期范围
const dateRange = ref([])
// 定义响应式变量来存储总天数
const totalDays = ref(0);
// 定义响应式变量来存储剩余小时数
const remainingHours = ref(0);


//计算某一天的请假时长
const calculateDailyHours = (date: Date, start: Date, end: Date) => {
  console.log("calculateDailyHours方法执行")
  let dailyHours = 0;
  const morningStart = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 8, 0, 0);
  const morningEnd = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0);
  const afternoonStart = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 14, 0, 0);
  const afternoonEnd = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 18, 0, 0);

  // 计算上午的请假时长
  if (start < morningEnd && end > morningStart) {
    const overlapStart = Math.max(start, morningStart);
    const overlapEnd = Math.min(end, morningEnd);
    dailyHours += (overlapEnd - overlapStart) / (1000 * 60 * 60);
  }

  // 计算下午的请假时长
  if (start < afternoonEnd && end > afternoonStart) {
    const overlapStart = Math.max(start, afternoonStart);
    const overlapEnd = Math.min(end, afternoonEnd);
    dailyHours += (overlapEnd - overlapStart) / (1000 * 60 * 60);
  }

  return dailyHours;
};

//处理日期选择变化的函数
const GetDateVule = (date: any) => {
  console.log("GetDateVule方法执行")

  if (date.length === 2) {
    const startDate = date[0];
    const endDate = date[1];
    let totalHours = 0;

    // 遍历日期范围，计算每天的请假时长
    let currentDate = new Date(startDate);
    while (currentDate <= endDate) {
      totalHours += calculateDailyHours(currentDate, startDate, endDate);
      currentDate.setDate(currentDate.getDate() + 1);
    }

    // 计算总天数
    totalDays.value = Math.floor(totalHours / 8);
    // 计算剩余小时数
    remainingHours.value = parseFloat((totalHours % 8).toFixed(1));
    //总小时
    ruleForm.leaveTime = totalDays.value * 8 + remainingHours.value;
  }
  //总 开始时间 至 结束时间
  ruleForm.leavePeriod = (moment(date[0]).format("yyyy-MM-DD HH:mm:ss") + " 至 " + moment(date[1]).format("yyyy-MM-DD HH:mm:ss")).toString();
  //报道时间
  // ruleForm.leaveEndTime = moment(date[1]).format("yyyy-MM-DD HH:mm:ss");
  ruleForm.leaveEndTime = date[1];
  //报道时间 修改为当前北京时间
  // ruleForm.leaveEndTime = moment().utcOffset(8).toISOString(); // 修改部分
  // console.log("开始时间", date[0])
  // console.log("结束时间", date[1])
}

//#endregion



//#region 反填部门上一级领导
//接受领导名称数组
const leaveLeader = ref([])

//获取领导名称(多人)
const FanTianleaveLeaderName = () => {
  axios.get(`https://localhost:7174/api/Approve/FanTianleaveLeaderName?DepId= ${store.ccstore.depId}&LevelRoleId=${parseInt(store.ccstore.levelRoleId) - 1}`).then(res => {
    //获取领导人
    leaveLeader.value = res.data.data.map((x: any) => x.nickName)
    // console.log(leaveLeader.value, "领导名称数组")
    //表单领导赋值
    ruleForm.leaveLeader = leaveLeader.value.join(" ")
    //获取审核等级
    ruleForm.levelRoleId = res.data.data[0].levelRoleId
  })
}
//#endregion


//#region  修改
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
//添加数据
const ruleForm = reactive<RuleForm>({
  "nickName": route.query.nickName, //ok
  "depId": route.query.depId, //ok
  "leaveType": route.query.leaveType,
  "leavePeriod": route.query.leavePeriod, //请假时间 至  ok
  "leaveTime": route.query.leaveTime,     //总工时 ok
  "leaveEndTime": route.query.leaveEndTime, //报道时间 ok
  "leaveReason": route.query.leaveReason,  //事由 ok
  "leaveLeader": "",  //部门领导
  "appStatus": 1,     //状态 ok
  "createTime": route.query.createTime,//创建时间 ok 
  "levelRoleId": route.query.levelRoleId,   //审核等级
  "userId": route.query.userId,
  "leaveId": route.query.leaveId,
})
const rules = reactive<FormRules<RuleForm>>({
  nickName: [
    { required: true, message: '请输入名称', trigger: 'blur' },
  ],
  leaveType: [
    { required: true, message: '请选择请假类型', trigger: 'blur' },
  ],
});


//修改
const submitForm = async (formEl: FormInstance | undefined) => {
  // ElMessage.success("修改成功")
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    // console.log(ruleForm, "表单内容")
    if (valid) {
      //已审批,不可再次审批
      if (IsStatus.value == true) {
        ElMessage.error("已审批,不可再次审批")
        return
      }
      //请假类别 数组转换为字符串
      // ruleForm.leaveType = ruleForm.leaveType.join(" ")
      // console.log(RecordForm1, "修改数据")
      axios.put("https://localhost:7272/api/Approve/UpdatLeaveModel", ruleForm).then(res => {
        if (res.data.code == 206) {
          ElMessage.success(res.data.msg)
          router.push("/ListLeaveModel")
        } else {
          ElMessage.success(res.data.msg)
        }
      })
    } else {
      // console.log('error submit!', fields)
    }
  })
}

//重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//#endregion



onMounted(() => {
  //获取领导名称(多人)
  FanTianleaveLeaderName()
  //时间反填
  FanTianData()
  //计算时间

  console.log(route.query, "传来的修改数据")
})


</script>

<style scoped></style>